import { EventTarget } from "cc";

export class Communicate {
  private static _instance: Communicate = null;
  private static uniqueId = Symbol(",");
  eTarget: EventTarget = null;

  static get getInstance(): Communicate {
    if (Communicate._instance === null) {
      Communicate._instance = new Communicate();
      Communicate._instance.eTarget = new EventTarget();

      this[Communicate.uniqueId] = Math.random().toString(36);
      console.log(this[Communicate.uniqueId]);
    }
    return Communicate._instance;
  }

  /**
   * 订阅事件
   * 注册事件目标的特定事件类型回调, 这种类型的时间应该被`emit`触发
   */
  on(represent: string, func: (...args: any[]) => void, target?: any) {
    this.eTarget.on(represent, func, target);
  }

  /**
   * 派发事件. 所有订阅了指定事件的目标将会接收到事件, 并可以作出响应
   * 通过事件名发送自定义事件
   */
  emit(represent: string, ...args: any[]) {
    this.eTarget.emit(represent, args);
  }

  /**
   * 取消订阅的事件
   * @param represent
   * @param func
   * @param target
   */
  off(represent: string, func: (...args: any[]) => void, target?: any) {
    this.eTarget.off(represent, func, target);
  }
}
